package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"
	"time"
)

//启动示例：go run main.go -d /Users/huanglixiang -s /Users/ssl_dir -p 8080 &
//访问 http://localhost:8080/  和 https://localhost:18080/

func main() {
	httpserver()
}

type httpServer struct {
	httpHandler http.Handler
}

func (server httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//解决浏览器提示一些莫名其妙的Provisional headers are shown 问题
	w.Header().Set("Access-Control-Allow-Origin","*")
	w.Header().Set("Access-Control-Allow-Headers","x-requested-with,Authorization,token,content-type,range")
	w.Header().Set("Access-Control-Allow-Credentials","true")
	w.Header().Set("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE, PUT")
	server.httpHandler.ServeHTTP(w,r)
}

//http服务器
func httpserver() {
	demo := "。完整命令参见 './localServer -d /Users/huanglixiang -s /Users/ssl_dir -p 8080 &'"

	var port,dir,SSL string
	flag.StringVar(&port, "p", "", "输入端口号，建议8080")
	flag.StringVar(&SSL, "s", "", "证书目录，如/Users/ssl_dir")
	flag.StringVar(&dir, "d", "", "根目录，绝对地址，如/Users/robin"+demo)
	flag.Parse()
	if port==""{
		fmt.Println("输入端口号，建议8080"+demo)
		os.Exit(0)
	}
	if SSL==""{
		fmt.Println("输入证书目录"+demo)
		os.Exit(0)
	}
	if dir==""{
		fmt.Println("根目录，绝对地址，如/Users/robi"+demo)
		os.Exit(0)
	}


	var server httpServer
	server.httpHandler = http.FileServer(http.Dir(dir))
	http.Handle("/", server)

	go func(){
		fmt.Println("http server port at "+port)
		err := http.ListenAndServe("0.0.0.0:"+port, nil)
		if err != nil {
			fmt.Println("ListenAndServe: ", err)
		}
	}()

	go func(){
		fmt.Println("https server port at 1"+port)
		//证书
		//brew install mkcert
		//mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1
		//更多见 https://zhuanlan.zhihu.com/p/100743934
		err := http.ListenAndServeTLS("0.0.0.0:1"+port, SSL+"/localhost.pem",SSL+"/localhost-key.pem",nil)
		if err != nil {
			fmt.Println("ListenAndServe: ", err)
		}
	}()

	time.Sleep(1000000000*time.Second)
}
